//
//  ESTActivityAchieveController.m
//  ESTSCRMAPP
//
//  Created by 李贤立 on 2018/10/12.
//  Copyright © 2018年 Capfer. All rights reserved.
//

#import "ESTActivityAchieveController.h"
#import "ESTActivityModel.h"
#import "ESTPickerTipView.h"
#import "TYZPickerTool.h"
#import "ESTCustomerInfoModel.h"
#import "ESTActivityCustomerInfoTableViewCell.h"
#import "ESTActivityDetailViewController.h"
#import "TYZIndicatorView.h"
#import "ESTFollowUpRecordViewController.h"
#define Height_Indicator         40
#define Height_ActivityNumberTip 40
@interface ESTActivityAchieveController ()<UITableViewDelegate, UITableViewDataSource>
/**
 *  时间选择器的标题
 */
@property(nonatomic, copy) NSString *datePickerTitle;
/**
 *  右上角标题
 */
@property(nonatomic, copy) NSString *rightTitle;
/**
 *  右上角按钮
 */
@property(nonatomic, strong) UIBarButtonItem *rightItem;
/**
 *  所有的活动
 */
@property(nonatomic, strong) NSArray<ESTActivityModel *> *activityData;
/**
 *  选择了第几个
 */
@property(nonatomic, assign) NSInteger activityInteger;
/**
 *  TableView
 */
@property(nonatomic, strong) TYZTableView *tableView;
/**
 *  开始时间
 */
@property(nonatomic, copy) NSString *start_date;
/**
 *  结束时间
 */
@property(nonatomic, copy) NSString *end_date;
/**
 *  数据源
 */
@property(nonatomic, strong) NSMutableArray<ESTCustomerInfoModel *> *modelArray;
/**
 *  请求的页码
 */
@property(nonatomic, assign) NSInteger page_num;
/**
 *  cell的高度
 */
@property(nonatomic, strong) NSMutableArray<NSNumber *> *cellHeightArray;
/**
 *  总共多少个数据
 */
@property(nonatomic, assign) NSInteger dataNumber;
/**
 *  是否删除了TableView
 */
@property(nonatomic, assign) BOOL isNoData;
/**
 *  第几种排序
 */
@property(nonatomic, assign) NSInteger sequenceCount;
/**
 *  排序方式
 YES 升序
 NO  降序
 */
@property(nonatomic, assign) BOOL sequenceMode;
@end

@implementation ESTActivityAchieveController
#pragma mark - 生命周期方法
- (void)viewDidLoad {
    [super viewDidLoad];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:self.rightTitle style:UIBarButtonItemStylePlain target:self action:@selector(didClickRightButton)];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.rightItem = rightItem;
    [self setupIndicatorView];
    [self acquireActivity];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self pullDownRefreshData];
}
#pragma mark - 设置UI
- (void)setupIndicatorView {
    TYZIndicatorModel *model = [[TYZIndicatorModel alloc] init];
    model.itemNumber = self.item;
    model.singleton = YES;
    TYZIndicatorView *indicator = [TYZIndicatorView indicatorWithTextArray:BaseInfo.achieveTextArray];
    indicator.model = model;
    [self.view addSubview:indicator];
    [indicator mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.mas_equalTo(Height_Indicator);
    }];
    WEAKSELF
    [indicator setDidSelectedItemBlock:^(NSArray<TYZSelectedModel *> *modelArray) {
        weakSelf.item = modelArray.firstObject.number;
        [weakSelf pullDownRefreshData];
    }];
}
- (void)setupActivityNumberTip {
    TYZView *numberView = [self.view viewWithTag:TAG_SIXTH_ACTIVITY_SELECTACTIVITYVIEW];
    if (numberView) {
        [numberView removeFromSuperview];
    }
    numberView = [[TYZView alloc] init];
    [self.view addSubview:numberView];
    numberView.tag = TAG_SIXTH_ACTIVITY_SELECTACTIVITYVIEW;
    [numberView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(Value_Height_PartPadding + Height_Indicator);
        make.height.mas_equalTo(Height_ActivityNumberTip);
    }];
    numberView.backgroundColor = TYZWhiteColor;
    // 总共多少个数据
    TYZLabel *numberLabel = [[TYZLabel alloc] init];
    numberLabel.text =[NSString stringWithFormat:@"%@：%ld",[@"共" S], (long)self.dataNumber];
    numberLabel.font = [UIFont systemFontOfSize:CoreInfo.fontSize];
    [numberView addSubview:numberLabel];
    [numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(numberView).offset(-20);
        make.centerY.equalTo(numberView);
    }];
    // 点击的排序图标
    TYZButton *sequenceButton = [TYZButton buttonWithType:UIButtonTypeCustom];
    [numberView addSubview:sequenceButton];
    [sequenceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(numberView);
        make.right.equalTo(numberLabel.mas_left).offset(-10);
        make.height.width.mas_equalTo(20);
    }];
    sequenceButton.transform = CGAffineTransformMakeRotation(M_PI);
    [sequenceButton setImage:[UIImage imageNamed:@"arrow_sequence"] forState:UIControlStateNormal];
    [sequenceButton addTarget:self action:@selector(didClickSequenceButton:) forControlEvents:UIControlEventTouchUpInside];
    // 排序方式
    ESTPickerTipView *sequencePickerView = [[ESTPickerTipView alloc] init];
    sequencePickerView.title = BaseInfo.sequenceTextArray[self.sequenceCount];
    sequencePickerView.textColor = PickerTipViewTextColor_333;
    sequencePickerView.titleLabel.font = [UIFont systemFontOfSize:CoreInfo.fontSize];
    sequencePickerView.dataArray = BaseInfo.sequenceTextArray;
    sequencePickerView.pickerTitle = [@"选择排序方式" S];
    sequencePickerView.selectedValue = @[BaseInfo.sequenceTextArray[self.sequenceCount]];
    [numberView addSubview:sequencePickerView];
    [sequencePickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(numberView);
        make.right.equalTo(sequenceButton.mas_left).offset(-10);
    }];
    WEAKSELF
    [sequencePickerView setDidChooseNumberBlock:^(NSArray<NSNumber *> *numberArray) {
        weakSelf.sequenceCount = [numberArray.lastObject integerValue];
    }];
    sequenceButton.hidden = YES;
    sequencePickerView.hidden = YES;
    // 选择活动
    __block NSString *name = [@"选择活动" S];
    [self.activityData enumerateObjectsUsingBlock:^(ESTActivityModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.ACTIVITY_ID isEqualToString:self.activity_id]) {
            name = obj.ACTIVITY_NAME;
            *stop = YES;
        }
    }];
    ESTPickerTipView *activityPickerView = [[ESTPickerTipView alloc] init];
    activityPickerView.title = name;
    activityPickerView.textColor = PickerTipViewTextColor_333;
    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:self.activityData.count];
    [self.activityData enumerateObjectsUsingBlock:^(ESTActivityModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [arrM addObject:obj.ACTIVITY_NAME];
    }];
    activityPickerView.titleLabel.font = [UIFont systemFontOfSize:CoreInfo.fontSize];
    activityPickerView.dataArray = [arrM mutableCopy];
    activityPickerView.pickerTitle = [@"选择活动" S];
    activityPickerView.selectedValue = @[name];
    [numberView addSubview:activityPickerView];
    [activityPickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(numberView);
        make.left.equalTo(numberView).offset(20);
    }];
    [activityPickerView setDidChooseNumberBlock:^(NSArray<NSNumber *> *numberArray) {
        weakSelf.activityInteger = [numberArray.lastObject integerValue];
    }];
}
- (void)setupTableView {
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view).offset(Height_ActivityNumberTip + Height_Indicator + Value_Height_PartPadding);
    }];
    [self setupTableViewHeader];
}
- (void)pullDownRefreshData {
    self.page_num = 1;
    [self.modelArray removeAllObjects];
    [self.cellHeightArray removeAllObjects];
    [self acquireData];
}
- (void)pullUpLoadMore {
    self.page_num++;
    [self acquireData];
}
- (void)setupTableViewHeader {
    WEAKSELF
    self.tableView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        [weakSelf pullDownRefreshData];
    }];
}
- (void)setupTableViewFooter {
    WEAKSELF
    self.tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [weakSelf pullUpLoadMore];
    }];
}
- (void)sequenceRefresh {
    [self setupActivityNumberTip];
    
}
#pragma mark - action
// 请求活动列表数据
- (void)acquireActivity {
    WEAKSELF
    [ESTActivityModel requestAllActivitySuccess:^(NSArray<ESTActivityModel *> *modelArray) {
        weakSelf.activityData = modelArray;
    } failure:^(NSString *error) {
        weakSelf.activityData = nil;
        [TYZLoadingView showError:NetworkUnusual];
    }];
}
// 请求单个活动下所有数据
- (void)acquireData {
    WEAKSELF
    [TYZLoadingView showMessage:nil];
    [ESTCustomerInfoModel requestAchieveDataWithItemCode:BaseInfo.achieveCodeArray[self.item] activity_id:self.activity_id start_date:self.start_date end_date:self.end_date page_num:self.page_num success:^(NSArray<ESTCustomerInfoModel *> *modelArray, NSInteger dataNumber) {
        [TYZLoadingView hideHUD];
        [weakSelf handleModelArray:modelArray dataNumber:dataNumber];
        [weakSelf.tableView.mj_header endRefreshing];
    } failure:^(NSString *error) {
        [TYZLoadingView showError:NetworkUnusual];
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf handleModelArray:nil dataNumber:0];
    }];
}
- (void)handleModelArray:(NSArray<ESTCustomerInfoModel *> *)modelArray dataNumber:(NSInteger)dataNumber {
    if (self.dataNumber != dataNumber) {
        self.dataNumber = dataNumber;
        [self setupActivityNumberTip];
    }
    if (modelArray.count > 0) {
        [self.tableView.mj_footer endRefreshing];
        [self.modelArray addObjectsFromArray:modelArray];
        [self.cellHeightArray addObjectsFromArray:[self cellHeightFromDataArray:modelArray]];
        if (modelArray.count < Request_PageSize_Normal) {
            self.page_num--;
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    } else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    if (self.modelArray.count > 0) {
        [self.view removeNoDataImage];
        if (self.isNoData) {
            self.isNoData = NO;
            [self setupTableView];
        } else {
            [self.tableView reloadData];
        }
        if (self.modelArray.count < Request_PageSize_Normal) {
            [self.tableView.mj_footer removeFromSuperview];
        } else {
            if (self.tableView.mj_footer == nil) {
                [self setupTableViewFooter];
            }
        }
    } else {
        self.isNoData = YES;
        [self.tableView removeFromSuperview];
        WEAKSELF
        [self.view noDataWithClick:^{
            [weakSelf pullDownRefreshData];
        }];
    }
}
- (void)didClickRightButton {
    TYZDatePickerMode datePickerMode = self.dateType == 2 ? DatePickerMode_YearMonth : DatePickerMode_Date;
    WEAKSELF
    [TYZPickerTool showDatePickerWithTitle:self.datePickerTitle dateString:self.rightTitle datePickerMode:datePickerMode complement:^(NSString *dateString) {
        weakSelf.rightTitle = dateString;
    }];
}
- (void)didClickSequenceButton:(TYZButton *)button {
    button.transform = CGAffineTransformRotate(button.transform, M_PI);
    self.sequenceMode = !self.sequenceMode;
    if (self.sequenceMode) {
        NSLog(@"升序");
    } else {
        NSLog(@"降序");
    }
}
// 计算cell的高度
- (NSArray<NSNumber *> *)cellHeightFromDataArray:(NSArray<ESTCustomerInfoModel *> *)dataArray {
    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:dataArray.count];
    [dataArray enumerateObjectsUsingBlock:^(ESTCustomerInfoModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSInteger remarkLines = [obj.POSITION1 componentsSeparatedByString:@"\\r\\n"].count;
        if ([obj.POSITION1 hasSuffix:@"\\r\\n"]) {
            remarkLines--;
        }
        /**
         高度的计算方法
         1，70是横线以及横线上面的固定部分高度。
         2，如果是“未成功沟通“一项，则有三行内容显示，否则为两行
         3，备注一栏有多少行，高度相应增加。
         4，注意加上上下的边距
         */
        CGFloat cellHeight =
        CustomerInfoTableViewCell_FirstPartHeight
        + (self.item == 2 ? ActivityAchieveTableViewCell_ContentLineHeight * 3 : ActivityAchieveTableViewCell_ContentLineHeight * 2)
        + remarkLines * ActivityAchieveTableViewCell_RemarkLineHeight + ActivityAchieveTableViewCell_LinePadding * 2.5;
        [arrM addObject:@(cellHeight)];
    }];
    return [arrM mutableCopy];
}
#pragma mark - UITableViewDelegate, UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return Value_Height_PartPadding;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    TYZView *view = [[TYZView alloc] init];
    view.backgroundColor = ESTBackgroundColor;
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self.cellHeightArray[indexPath.section] floatValue];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.modelArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ESTActivityCustomerInfoTableViewCell *cell = [ESTActivityCustomerInfoTableViewCell creatActivityAchieveTableViewCell:tableView item:self.item];
    cell.model = self.modelArray[indexPath.section];
    WEAKSELF
    [cell setDidClickActivityNameBlock:^(NSString *activity_id) {
        ESTActivityDetailViewController *controller = [[ESTActivityDetailViewController alloc] init];
        controller.activity_id = weakSelf.activity_id;
        [weakSelf.navigationController pushViewController:controller animated:YES];
    }];
    [cell setComplementDialBlock:^(NSString *duration) {
        ESTFollowUpRecordViewController *controller = [[ESTFollowUpRecordViewController alloc] init];
        controller.followUpType = FollowUpRecordType_Normal;
        controller.duration = duration;
        controller.followUpType = FollowUpRecordType_Phone;
        controller.model = weakSelf.modelArray[indexPath.section];
        [weakSelf.navigationController pushViewController:controller animated:YES];
    }];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ESTFollowUpRecordViewController *controller = [[ESTFollowUpRecordViewController alloc] init];
    controller.followUpType = FollowUpRecordType_Normal;
    controller.model = self.modelArray[indexPath.section];
    [self.navigationController pushViewController:controller animated:YES];
}
#pragma mark - setter & getter
- (TYZTableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[TYZTableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (void)setDateType:(NSInteger)dateType {
    _dateType = dateType;
    switch (dateType) {
        case 0:
            self.mainTitle = @"今天的业绩详情";
            self.datePickerTitle = @"选择哪一天";
            self.rightTitle = [[NSDate date] formatterDate:@"yyyy-MM-dd"];
            break;
        case 1:
            self.mainTitle = @"本周的业绩详情";
            self.datePickerTitle = @"选择周内的任意一天";
            self.rightTitle = [[NSDate date] formatterDate:@"yyyy-MM-dd"];
            self.start_date = [TYZTool weekTypeDayArrayWithDateString:self.rightTitle].firstObject;
            break;
        case 2:
            self.mainTitle = @"本月的业绩详情";
            self.datePickerTitle = @"选择月份";
            self.rightTitle = [[NSDate date] formatterDate:@"yyyy-MM"];
            break;
        default:
            break;
    }
}
- (void)setActivityData:(NSArray<ESTActivityModel *> *)activityData {
    _activityData = activityData;
    [self setupTableView];
}
- (void)setActivityInteger:(NSInteger)activityInteger {
    _activityInteger = activityInteger;
    self.activity_id = self.activityData[activityInteger].ACTIVITY_ID;
    [self setupActivityNumberTip];
    [self pullDownRefreshData];
}
- (void)setSequenceCount:(NSInteger)sequenceCount {
    _sequenceCount = sequenceCount;
    [self sequenceRefresh];
}
- (NSMutableArray<ESTCustomerInfoModel *> *)modelArray {
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}
- (NSMutableArray<NSNumber *> *)cellHeightArray {
    if (_cellHeightArray == nil) {
        _cellHeightArray = [NSMutableArray array];
    }
    return _cellHeightArray;
}
- (void)setRightTitle:(NSString *)rightTitle {
    _rightTitle= rightTitle;
    switch (self.dateType) {
        case 0:
            self.start_date = rightTitle;
            self.end_date = rightTitle;
            break;
        case 1: {
            NSArray *arr = [TYZTool weekTypeDayArrayWithDateString:rightTitle];
            self.start_date = arr.firstObject;
            self.end_date = arr.lastObject;
        }
            break;
        case 2: {
            NSArray *arr = [TYZTool monthTypeDayArrayWithDateString:rightTitle];
            self.start_date = arr.firstObject;
            self.end_date = arr.lastObject;
        }
            break;
        default:
            break;
    }
    if (self.rightItem) {
        self.rightItem.title = rightTitle;
        [self acquireData];
    }
}
@end
